<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/20 0020
 * Time: 23:38
 */

namespace Lib\Core;

use Swoole\Http\Request;
use Swoole\Http\Response;

/**
 * @description:路由的实现
 * @auth:yfl
 * @email:554665488@qq.com
 * Class Route
 * @package Lib\Core
 */
class Router
{
    private static $route;
    private static $instance;

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * @description:记录我们的路由配置信息
     * @auth:yfl
     * @email:554665488@qq.com
     * @param $method
     * @param $arguments
     */
    public static function __callStatic($method, $arguments)
    {
        // TODO: Implement __callStatic() method.
        self::$route[$method][] = $arguments;
    }

    public function dispatch(Request $request, Response $response)
    {
        $server = $request->server;
        //获取到默认的路由做一个自动加载
        if ('/favicon.ico' == $server['path_info']) {
            return '';
        }
        //地址栏地址
        $method = $server['request_method'];
        $path = $server['path_info'];

        switch ($method) {
            case 'GET':
                //遍历路由表
                foreach (self::$route[strtolower($method)] as $v) {
                    //判断路径是否在已经注册的路由上
                    if (in_array($path, $v)) {
                        return $this->get($request, $response, $v[1]);
                    }
                }
                break;
            case 'POST':
                break;
        }
    }

    /**
     * @description:响应路由
     * @auth:yfl
     * @email:554665488@qq.com
     * @param Request $request
     * @param Response $response
     * @param $param
     */
    private function get(Request $request, Response $response, $param)
    {
        if ($param instanceof \Closure) {
            $result = $param();
        } else {
            $controllerMethod = explode('@', $param);
            $namespace = "App\Controller"; //命名空间
            $class = $namespace . '\\' . ucfirst($controllerMethod[0]);
            $method = $controllerMethod[1];
            $result = (new $class)->$method($request);
        }
        //var_dump($result);
        $response->end($result);
    }

}